package com.hjk;

import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.setting.dialect.Props;
import cn.hutool.setting.dialect.PropsUtil;
import com.aliyun.auth.credentials.Credential;
import com.aliyun.auth.credentials.provider.StaticCredentialProvider;
import com.aliyun.sdk.service.alidns20150109.AsyncClient;
import com.aliyun.sdk.service.alidns20150109.models.*;
import com.google.gson.Gson;
import com.hjk.util.IPUntils;
import darabonba.core.client.ClientOverrideConfiguration;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;

public class AliyunDDNSMain {
    public static void main(String[] args) throws ExecutionException, InterruptedException {
        Props ddns = PropsUtil.getFirstFound("ddns");
        String domain = ddns.getStr("domain");
        String accessKeyId = ddns.getStr("accesskey_id");
        String accessKeySecret = ddns.getStr("accesskey_secret");
        String outIp = null;
        while (true) {
            try {
                String tempOutIp = IPUntils.getOutIPV4();
                if (StrUtil.equals(tempOutIp, outIp)) {
                    Thread.sleep(10000);
                    continue;
                }
                outIp = tempOutIp;
                StaticCredentialProvider provider = StaticCredentialProvider.create(Credential.builder()
                        .accessKeyId(accessKeyId)
                        .accessKeySecret(accessKeySecret)
                        .build());

                AsyncClient client = AsyncClient.builder()
                        .credentialsProvider(provider)
                        .overrideConfiguration(
                                ClientOverrideConfiguration.create()
                                        .setEndpointOverride("alidns.cn-hangzhou.aliyuncs.com")
                        )
                        .build();
                Map<String, String> rr2RecordId = new HashMap<>();
                Map<String, String> rr2Value = new HashMap<>();
                {
                    DescribeDomainRecordsRequest describeDomainRecordsRequest = DescribeDomainRecordsRequest.builder()
                            .domainName(domain)
                            .type("A")
                            .pageNumber(1L)
                            .pageSize(50L)
                            .build();
                    CompletableFuture<DescribeDomainRecordsResponse> describeDomainRecordsResponseCompletableFuture = client.describeDomainRecords(describeDomainRecordsRequest);
                    DescribeDomainRecordsResponse describeDomainRecordsResponse = describeDomainRecordsResponseCompletableFuture.get();
                    String s = new Gson().toJson(describeDomainRecordsResponse);
                    JSONObject jsonObject = new JSONObject(s);
                    JSONArray jsonArray = jsonObject.getJSONObject("body").getJSONObject("domainRecords").getJSONArray("record");
                    for (Object o : jsonArray) {
                        JSONObject recordJson = (JSONObject) o;
                        rr2RecordId.put(recordJson.getStr("rr"), recordJson.getStr("recordId"));
                        rr2Value.put(recordJson.getStr("rr"), recordJson.getStr("value"));
                    }
                }
                String[] rrList = new String[]{"@", "www"};
                for (String rr : rrList) {
                    System.out.println(outIp);
                    System.out.println(rr);
                    try {
                        if (rr2RecordId.containsKey(rr)) {
                            if (!outIp.equals(rr2Value.get(rr))) {
                                UpdateDomainRecordRequest request = UpdateDomainRecordRequest.builder()
                                        .recordId(rr2RecordId.get(rr))
                                        .rr(rr)
                                        .type("A")
                                        .value(outIp)
                                        .build();
                                CompletableFuture<UpdateDomainRecordResponse> response = client.updateDomainRecord(request);
                                UpdateDomainRecordResponse resp = response.get();
                                System.out.println(new Gson().toJson(resp));
                            }
                        } else {
                            AddDomainRecordRequest request = AddDomainRecordRequest.builder()
                                    .domainName(domain)
                                    .rr(rr)
                                    .type("A")
                                    .value(outIp)
                                    .build();
                            CompletableFuture<AddDomainRecordResponse> response = client.addDomainRecord(request);
                            AddDomainRecordResponse resp = response.get();
                            System.out.println(new Gson().toJson(resp));
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
                client.close();
            } catch (Exception e) {
                e.printStackTrace();
            }
        }

    }
}
